/*
 * Copyright 2019-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.aot.test;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.function.Supplier;

import org.springframework.context.ApplicationContextInitializer;
import org.springframework.test.context.SmartContextLoader;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;

/**
 * {@code AotTestMappings} provides mappings from test classes to AOT context loaders
 * and context initializers.
 * <p/>
 * If a test class is not {@linkplain #isSupportedTestClass(Class) supported} in
 * AOT mode, {@link #getContextLoader(Class)} and {@link #getContextInitializerClass(Class)}
 * will return {@code null}.
 * <p/>
 * Reflectively accesses {@value #INITIALIZER_NAME} generated by the
 * {@code TestContextAotProcessor} in the {@code spring-aot-test} module to retrieve
 * the mappings.
 *
 * @author Stephane Nicoll
 * @author Sam Brannen
 */
class AotTestMappings {

	private static final String INITIALIZER_NAME = "org.springframework.aot.TestContextBootstrapInitializer";

	private final Map<String, Supplier<SmartContextLoader>> contextLoaders;

	private final Map<String, Class<? extends ApplicationContextInitializer<?>>> contextInitializers;

	AotTestMappings(Map<String, Supplier<SmartContextLoader>> contextLoaders,
			Map<String, Class<? extends ApplicationContextInitializer<?>>> contextInitializers) {
		this.contextLoaders = contextLoaders;
		this.contextInitializers = contextInitializers;
	}

	@SuppressWarnings("unchecked")
	AotTestMappings(String initializerClassName) {
		this(loadMap(initializerClassName, "getContextLoaders"), loadMap(initializerClassName, "getContextInitializers"));
	}

	AotTestMappings() {
		this(INITIALIZER_NAME);
	}

	/**
	 * Determine if the specified test class has an AOT-generated application context.
	 * <p>If this method returns {@code true}, {@link #getContextLoader(Class)} and
	 * {@link #getContextInitializerClass(Class)} should return non-null values.
	 */
	boolean isSupportedTestClass(Class<?> testClass) {
		return this.contextLoaders.containsKey(testClass.getName());
	}

	/**
	 * Get the AOT {@link SmartContextLoader} for the specified test class.
	 * @return the AOT context loader, or {@code null} if there is no AOT context
	 * loader for the specified test class
	 * @see #isSupportedTestClass(Class)
	 */
	SmartContextLoader getContextLoader(Class<?> testClass) {
		Supplier<SmartContextLoader> supplier = this.contextLoaders.get(testClass.getName());
		return (supplier != null) ? supplier.get() : null;
	}

	/**
	 * Get the AOT {@link ApplicationContextInitializer} for the specified test class.
	 * @return the AOT context initializer, or {@code null} if there is no AOT context
	 * initializer for the specified test class
	 * @see #isSupportedTestClass(Class)
	 */
	Class<? extends ApplicationContextInitializer<?>> getContextInitializerClass(Class<?> testClass) {
		return this.contextInitializers.get(testClass.getName());
	}

	@SuppressWarnings("rawtypes")
	private static Map loadMap(String className, String methodName) {
		try {
			Class<?> type = ClassUtils.forName(className, null);
			Method method = ReflectionUtils.findMethod(type, methodName);
			if (method == null) {
				throw new IllegalStateException(String.format("No %s() method found on %s", methodName, type.getName()));
			}
			return (Map) ReflectionUtils.invokeMethod(method, null);
		}
		catch (IllegalStateException ex) {
			throw ex;
		}
		catch (Exception ex) {
			throw new IllegalStateException(String.format("Failed to load %s() method in %s", methodName, className), ex);
		}
	}

}
